package org.example.security.handle;

import com.alibaba.fastjson2.JSON;
import org.example.common.constants.HttpStatus;
import org.example.common.util.web.AjaxResult;
import org.example.common.util.web.ServletUtils;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @version 1.0.0
 * @className: CustomExpiredSessionStrategyImpl
 * @description: 自定义并发会话失效策略
 * @author: LiJunYi
 * @create: 2022/7/28 10:24
 */
@Component
public class CustomExpiredSessionStrategyImpl implements SessionInformationExpiredStrategy, Serializable
{

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException
    {
        int code = HttpStatus.CONFLICT;
        String msg = "您的账号已经在其它设备登录,如果非本人操作，请立即修改密码！";
        HttpServletResponse response = event.getResponse();
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
